package com.hushao.lims.weblims.service.impl;

import com.hushao.lims.weblims.domain.ClassInfo;
import com.hushao.lims.weblims.domain.ClassroomInfo;
import com.hushao.lims.weblims.domain.LabRegistration;
import com.hushao.lims.weblims.domain.TeacherInfo;
import com.hushao.lims.weblims.repository.ClassRepository;
import com.hushao.lims.weblims.repository.ClassroomRepository;
import com.hushao.lims.weblims.repository.LabRegistrationRepository;
import com.hushao.lims.weblims.service.LabRegistrationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 930588706
 * @date 18/1/21
 */
@Service
public class LabRegistrationServiceImpl implements LabRegistrationService {
    @Autowired
    private LabRegistrationRepository labRegistrationRepository;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private ClassRepository classRepository;
    @Autowired
    private ClassroomRepository classroomRepository;
    @Override
    public Page<LabRegistration> listLabRegistrationByTeacherNameLikeClassNameLikeClassroomNameLike(String teacherName, String className, String classroomName, Pageable pageable) {
        teacherName="%"+teacherName+"%";
        className="%"+className+"%";
        classroomName="%"+classroomName+"%";
        return labRegistrationRepository.findByTeacherInfo_TeacherNameLikeAndClassInfo_ClassNameLikeAndClassroomInfo_ClassroomNameLike(teacherName,className,classroomName,pageable);
    }

    @Override
    public LabRegistration getById(Long labRegistrationId) {
        return labRegistrationRepository.getOne(labRegistrationId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(LabRegistration labRegistration, String teacherNumber, String className, String classroomName) throws Exception {
        TeacherInfo teacher= (TeacherInfo) userDetailsService.loadUserByUsername(teacherNumber);
        ClassInfo classInfo=classRepository.findByClassName(className);
        ClassroomInfo classroom=classroomRepository.findByClassroomName(classroomName);
        if(classInfo==null){
            throw new Exception("没有此班级!");
        }
        if (classroom==null){
            throw new Exception("没有此实验室!");
        }
        String useTime=labRegistration.getUseTime();
        labRegistration.setUseTime(useTime.substring(0,2)+useTime.substring(3,5)+useTime.substring(6,10));
        labRegistration.setTeacherInfo(teacher);
        labRegistration.setClassInfo(classInfo);
        labRegistration.setClassroomInfo(classroom);
        labRegistrationRepository.save(labRegistration);
    }
}
